<template>
	<view class="chat_contro">
		<view class="head">
			<view class="head_li">
				<uni-icons type="back" size="30" color="#fff" class="icon_back" @click="navigBack"></uni-icons>
				<text>{{info}}</text>
				<uni-icons class="icon" type="list" size="28" color="#fff" @click="Navigator('friend')"></uni-icons>
			</view>
		</view>
		<scroll-view :scroll-y="isscroll" :scroll-top="scorllTop" class="body" @click="AIndex = null"
			@scrolltoupper="scrollToTop" :scroll-with-animation="scrollAnimation" @scroll="scroll">
			<!-- scroll-with-animation="true" -->
			<view v-for="(item,i) in allMsg" :key="i">
				<view class="time" v-show="isTimeshow(i,i-1)">{{formatDateTime(item.formatTime)}}</view>
				<view :class="(item.uid == myInfo.id) ? 'pop_right': 'pop_left'" v-show="(popIndex == i)">
					<view class="one" @click="DeleteMsg(i)" v-show="isOverTwoMinutes(item.formatTime)">删除</view>
					<view class="two" @click="">回复</view>
					<up-copy :content="item.msg">
						<view class="tre">复制</view>
					</up-copy>
				</view>
				<up-overlay :show="(popIndex != null)" opacity="0" zIndex="1" @click="popIndex = null"></up-overlay>
				<view :class="(item.uid == myInfo.id) ? 'msg_item_right' : 'msg_item_left'">
					<image :src="item.avatar" @click="Navigator('personal',item)"></image>
					<view class="msg_body">
						<view class="context" @click="popIndex = i">
							<text>{{item.msg}}</text>
						</view>
						<view class="sigh" v-show="item.status == 2 && item.uid == this.myInfo.id">
							<image src="../../static/chat-icons/sigh.png"></image>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="btom">
			<view class="chat_box">
				<view class="input">
					<input class="i_put" v-model="msg" :focus="dhcp" @blur="inputBlur" @focus="inputFocus"
						@keyboardheightchange="keyboard" />
				</view>
				<view class="send" @click="sendMsg">发送</view>
			</view>
			<view class="icons">
				<view v-for="(item,i) in icons" :key="i">
					<image :src="item.src" v-show="!(i == AIndex)" @click="cutIsConsActive(item,i)"></image>
					<image :src="item.activeSrc" v-show="(i == AIndex)" @click="cutIsConsActive(item,i)"
						:class="item.class"></image>
				</view>
			</view>
			<view class="hide">
				<image src="../../static/chat-icons/Stay_tuned.png"></image>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
	} from 'vuex'
	import {
		getMsgList,
		sendMsg,
		deleteMsg
	} from '../../common/api';
	export default {
		computed: {
			...mapState('info', ['myInfo'])
		},
		data() {
			return {
				info: '',
				msg: '',
				cId: '',
				onkeyHeight: 0, //底部弹出
				bodyHeight: 0, //消息框高度
				scorllTop: 0,
				initscoTop: 0,
				dhcp: false, //自动获取焦点
				keyDwom: false, //键盘是否弹下
				systemInfo: uni.getSystemInfoSync(),
				icons: [{
						src: '../../static/chat-icons/speech.png',
						activeSrc: '../../static/chat-icons/speech_active.png'
					},
					{
						src: '../../static/chat-icons/images.png',
						activeSrc: '../../static/chat-icons/images_active.png'
					},
					{
						src: '../../static/chat-icons/expression.png',
						activeSrc: '../../static/chat-icons/expression_active.png'
					},
					{
						src: '../../static/chat-icons/more_add.png',
						activeSrc: '../../static/chat-icons/more_add_active.png',
						class: 'more_active'
					}
				],
				AIndex: null,
				isMore: false,
				popIndex: null,
				pageNo: 1,
				stopPage: false,
				isscroll: true, // 允许滑动
				scrollAnimation: false, //滑动动作
				allMsg: [],
			};
		},
		onLoad(val) {
			this.info = val.nickName;
			this.cId = val.cId;
			this.InitScorllTop();
			this.getAddMsgList();
		},
		methods: {
			getAddMsgList() {
				getMsgList({
					CId: this.cId,
					pageNo: 1,
					pageSize: 50
				}).then((res) => {
					let resData = res.data;
					if (res) {
						const uniqueMessages = resData.filter(newMsg => {
							return !this.allMsg.some(existingMsg => existingMsg.id === newMsg.id);
						});
						this.allMsg.push(...uniqueMessages.reverse());
						setTimeout(() => {
							this.scorllTop += this.initscoTop;
						}, 50);
					}
				});
			},
			getMegTopList(val) {
				if (this.stopPage) return;
				getMsgList({
					CId: val,
					pageNo: this.pageNo,
					pageSize: 50
				}).then((res) => {
					let resData = res.data;
					if (res) {
						const uniqueMessages = resData.filter(newMsg => {
							return !this.allMsg.some(existingMsg => existingMsg.id === newMsg.id);
						});
						this.allMsg.unshift(...uniqueMessages.reverse())
						if (resData.length == 50) {
							this.pageNo++;
						}
						if (resData.length == 0) {
							this.stopPage = true;
						}
					}
				})
			},
			navigBack() {
				uni.switchTab({
					url: '/pages/message/message'
				})
			},
			Navigator(val, item) {
				if (val == 'friend') {
					uni.navigateTo({
						url: '/subpkg/friend_details/friend_details?cid=' + this.cId
					})
				}
				if (val == 'personal') {
					uni.navigateTo({
						url: '/subpkg/personal_details/personal_details?fid=' + item.uid
					})
				}
			},
			cutIsConsActive(item, i) {
				if (this.AIndex == i) {
					this.AIndex = null;
					return
				}
				// if(!this.keyDwom) return
				setTimeout(() => {
					this.AIndex = i;
				}, 100);
			},
			InitScorllTop() {
				let system = this.systemInfo.uniPlatform;
				let head = this.systemInfo.windowWidth / 750 * 150;
				let botom = this.systemInfo.windowWidth / 750 * 200;
				let bodyheight = this.systemInfo.windowHeight - head - botom;
				this.bodyHeight = bodyheight + 'px';

				setTimeout(() => {
					this.scorllTop = 100000;
				}, 200);
				if (system === 'web') {
					try {
						const lastHeight = window.innerHeight;
						window.addEventListener('resize', () => {
							const currentHeight = window.innerHeight;
							// 检查高度是否有变化
							if (lastHeight > currentHeight) {
								this.AIndex = null;
								this.keyDwom = false;
								const keyboardHeight = lastHeight - currentHeight;
								let numValue = parseFloat(this.bodyHeight);

								this.bodyHeight = (numValue - keyboardHeight) + 'px';
								setTimeout(() => {
									this.scorllTop = (numValue + this.initscoTop)
								}, 100);
							} else {
								this.bodyHeight = bodyheight + 'px';

								setTimeout(() => {
									this.scorllTop = this.initscoTop
									this.keyDwom = true;
								}, 100);
							}
						});
					} catch {}
				}
				if (system === 'app') {
					uni.onKeyboardHeightChange(res => {
						// this.bodyHeight = '300rpx'
						if (res.height > 0) {
							this.bodyHeight = (parseFloat(this.bodyHeight) - res.height) + 'px';
							setTimeout(() => {
								this.scorllTop = (parseFloat(this.bodyHeight) + this.initscoTop)
							}, 100);
							return;
						}
						this.bodyHeight = bodyheight + 'px'
						setTimeout(() => {
							this.scorllTop = this.initscoTop
							this.keyDwom = true;
						}, 100);
					})
				}
			},
			sendMsg() {
				if (this.msg == '') return
				this.dhcp = true;
				sendMsg({
					uId: this.myInfo.id,
					cId: this.cId,
					msg: this.msg
				}).then((res) => {
					this.getAddMsgList();
					this.msg = '';
				})
			},
			scrollToTop() {
				this.getMegTopList(this.cId);
			},
			scroll(e) {
				if (this.initscoTop == 0) {
					this.initscoTop = e.detail.scrollHeight;
				}
				if (e.detail.scrollTop == 0) {
					// this.isscroll = false;
					this.scorllTop = e.detail.scrollHeight - this.initscoTop;
					// this.isscroll = true;
					this.initscoTop = e.detail.scrollHeight;
				}
			},
			DeleteMsg(i) {
				this.popIndex = null;
				deleteMsg({
					uId: this.myInfo.id,
					mId: this.allMsg[i].id
				})
				this.allMsg.splice(i, 1);
			},
			isOverTwoMinutes(val) {
				const now = new Date();
				const date = new Date(val);
				const diff = now - date;
				return diff < 120 * 1000;
			},
			inputFocus() {
				if (this.AIndex != null) {
					let head = this.systemInfo.windowWidth / 750 * 150;
					let botom2 = this.systemInfo.windowWidth / 750 * 200;
					let bodyheight = this.systemInfo.windowHeight - head - botom2;
					this.bodyHeight = bodyheight + 'px'
					setTimeout(() => {
						this.scorllTop = this.initscoTop;
					}, 100);
				}
				this.AIndex = null
			},
			inputBlur() {
				this.dhcp = false;
			},
			keyboard(e) {
				// this.bodyHeight = (parseFloat(this.bodyHeight) - e.detail.height)+'px';
				// console.log(e.detail.height);
			},
			getCurrentTime() {
				const now = new Date(); // 获取当前时间
				const year = now.getFullYear(); // 年份
				const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 月份，加1因为getMonth()返回的月份是从0开始的
				const day = now.getDate().toString().padStart(2, '0'); // 日期
				const hours = now.getHours().toString().padStart(2, '0'); // 小时
				const minutes = now.getMinutes().toString().padStart(2, '0'); // 分钟
				const seconds = now.getSeconds().toString().padStart(2, '0'); // 秒数

				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			formatDateTime(dateString) {
				// 解析日期字符串为Date对象
				const inputDate = new Date(dateString);

				// 获取今天是周几（0 = 星期日，1 = 星期一，...，6 = 星期六）
				const today = new Date();
				today.setHours(0, 0, 0, 0); // 重置时间部分，以便比较日期

				// 获取当前年份
				const currentYear = today.getFullYear();
				const inputYear = inputDate.getFullYear();

				// 设置星期数组
				const daysOfWeek = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];

				// 计算输入日期与今天相差的天数
				const diffTime = today - inputDate;
				const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

				// 获取输入日期的月份和日期
				const month = (inputDate.getMonth() + 1).toString().padStart(2, '0'); // 月份，需要+1因为getMonth()是从0开始计数
				const day = inputDate.getDate().toString().padStart(2, '0');

				let result;

				if (diffDays === 0) {
					// 今天
					result = `${inputDate.getHours()}:${String(inputDate.getMinutes()).padStart(2, '0')}`;
				} else if (diffDays === 1) {
					// 昨天
					result = `昨天 ${inputDate.getHours()}:${inputDate.getMinutes()}`;
				} else if (diffDays === 2) {
					// 前天
					result = `前天 ${inputDate.getHours()}:${inputDate.getMinutes()}`;
				} else if (diffDays < 7) {
					// 超过昨天但在一周之内
					result = daysOfWeek[inputDate.getDay()];
				} else if (inputYear === currentYear) {
					// 今年但不在一周内
					result = `${month}-${day}`;
				} else {
					// 超出一年范围
					result =
						`${inputYear.toString().substring(2)}/${month}/${day} ${inputDate.getHours()}:${inputDate.getMinutes()}`;
				}
				return result;
			},
			isTimeshow(now, back) {
				try {
					let time1 = this.allMsg[now].formatTime;
					let time2 = this.allMsg[back].formatTime;
					const timeDiff = new Date(time1) - new Date(time2);
					const tenMinutes = 5 * 60 * 1000;
					return timeDiff > tenMinutes;
				} catch {
					return true;
				}
			}
		},
		watch: {
			AIndex(newVal, oldVal) {
				let head = this.systemInfo.windowWidth / 750 * 150;
				let botom = this.systemInfo.windowWidth / 750 * 400;

				let botom2 = this.systemInfo.windowWidth / 750 * 200;

				let bodyheight1 = this.systemInfo.windowHeight - head - botom2;

				let bodyheight = this.systemInfo.windowHeight - head - botom - botom2;

				if (newVal != null) {
					if (typeof oldVal === 'number') return;
					this.onkeyHeight = '-400rpx'
					setTimeout(() => {
						this.scorllTop = this.initscoTop * 2;
					}, 100);
					this.bodyHeight = bodyheight + 'px';
				} else {
					this.onkeyHeight = 0
					setTimeout(() => {
						this.scorllTop = this.initscoTop;
					}, 100);
					this.bodyHeight = bodyheight1 + 'px'
				}
			}
		}
	}
</script>

<style lang="scss">
	.chat_contro {
		height: 100vh;

		.head {
			background: linear-gradient(90deg, rgba(122, 220, 241, 1) 0%, rgba(43, 163, 242, 1) 48%);
			width: 750rpx;
			height: 150rpx;
			// position: fixed;

			.head_li {
				// position: absolute;
				bottom: 0;
				width: 750rpx;
				height: 110rpx;
				display: flex;
				justify-content: space-between;
				// line-height: 100rpx;
				padding: 40rpx 0rpx;

				text {
					color: #fff;
					font-size: 35rpx;
					opacity: 0.8;
					padding: 15rpx;
					display: flex;
					line-height: 80rpx;
				}

				.icon_back {
					padding: 15rpx 20rpx;
				}

				.icon {
					padding: 15rpx 30rpx;
				}
			}
		}

		.body {
			height: v-bind(bodyHeight);
			background-color: #e6e6e6;
			// position: fixed;
			top: 150rpx;
			overflow-anchor: auto;

			.time {
				height: 50rpx;
				color: #868686;
				font-size: 26rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				padding: 10rpx;
			}

			%pop {
				width: 300rpx;
				height: 50rpx;
				display: flex;
				justify-content: space-around;
				align-items: center;
				background-color: #404040;
				color: #e4e4e4;
				position: absolute;
				left: 60rpx;
				margin-top: -30rpx;
				border-radius: 20rpx;
				z-index: 2;
				font-size: 22rpx;

				:active {
					background-color: #949494;
				}

				&:after {
					content: "";
					display: block;
					border-width: 8px;
					position: absolute;
					top: 0rpx;
					right: 140rpx;
					border-style: solid dashed dashed solid;
					border-color: #404040 transparent transparent transparent;
					font-size: 0;
					line-height: 0;
				}

				&:after {
					top: 26px;
					border-color: #404040 transparent transparent transparent;
				}
			}

			.pop_left {
				@extend %pop;
				position: absolute;
				left: 60rpx;
				margin-top: -30rpx;
			}

			.pop_right {
				@extend %pop;
				position: absolute;
				left: 360rpx;
				margin-top: -40rpx;
			}

			.msg_item_left {
				width: 750rpx;
				min-height: 100rpx;
				display: flex;
				align-items: center;
				padding: 10rpx;
				position: relative;

				image {
					position: absolute;
					top: 20rpx;
					width: 90rpx;
					height: 90rpx;
					border-radius: 40rpx;
				}


				.msg_body {
					display: flex;
					justify-content: space-between;

					.sigh {
						margin-left: -80rpx;

						image {
							margin-top: 15rpx;
							width: 50rpx;
							height: 50rpx;
						}

						&:active {
							transform: scale(0.98);
							transition: transform 0.1s;
						}
					}

					.context {
						@extend %base;
						background-color: #fff;

						&:active {
							background-color: #c3c3c3;
						}
					}
				}
			}

			.msg_item_right {
				width: 730rpx;
				min-height: 100rpx;
				display: flex;
				flex-direction: row-reverse;
				align-items: center;
				padding: 10rpx;
				position: relative;

				image {
					position: absolute;
					top: 20rpx;
					width: 90rpx;
					height: 90rpx;
					border-radius: 40rpx;
				}

				.msg_body {
					display: flex;
					flex-direction: row-reverse;

					.sigh {
						margin-right: -30rpx;

						image {
							margin-top: 15rpx;
							margin-right: 20rpx;
							width: 50rpx;
							height: 50rpx;
						}

						&:active {
							transform: scale(0.98);
							transition: transform 0.1s;
						}
					}

					.context {
						@extend %base;
						background-color: #1ddaff;

						&:active {
							background-color: #1ecfff;
						}
					}
				}
			}

			%base {
				max-width: 400rpx;
				min-height: 80rpx;
				display: flex;
				align-items: center;
				margin: 10rpx 100rpx;
				padding: 0 20rpx;
				border-radius: 10rpx;

				text {
					color: #000;
					letter-spacing: 1rpx;
					padding: 10rpx 0;
					line-height: 40rpx;
				}
			}
		}

		.btom {
			height: 200rpx;
			width: 750rpx;
			background-color: #e7e7e7;
			transform: translateY(v-bind(onkeyHeight));
			transition: transform 0.1s;
			position: fixed;
			bottom: 0;

			.chat_box {
				height: 100rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.input {
					width: 600rpx;
					background-color: #fff;
					border-radius: 10rpx;
					height: 80rpx;
					margin: 0rpx 20rpx;
					display: flex;

					.i_put {
						width: 500rpx;
						height: 80rpx;
						font-size: 35rpx;
						font-weight: 400;
						color: #484848;
						padding: 0 20rpx;
					}
				}

				.send {
					background-color: rgba(24, 178, 244, 0.8);
					width: 120rpx;
					height: 80rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					color: #fff;
					font-size: 28rpx;
					border-radius: 15rpx;
					margin: 15rpx 10rpx 0 0;
					margin-bottom: 15rpx;

					&:active {
						background-color: rgba(24, 178, 244, 0.5);
						color: #dddddd;
						transform: scale(0.9);
						transition: transform 0.1s;
					}
				}
			}

			.icons {
				height: 80rpx;
				display: flex;
				justify-content: space-around;
				padding: 10rpx 0;
				border-bottom: 1rpx solid #000;

				image {
					width: 60rpx;
					height: 60rpx;
				}

				.more_active {
					transition: rotate 1s;
					animation: rotate 0.5s linear 1 forwards;

					@keyframes rotate {
						from {
							transform: rotate(0deg);
						}

						to {
							transform: rotate(135deg);
						}
					}
				}
			}

			.hide {
				height: 400rpx;
				background-color: #e3e3e3;

				image {
					width: 100rpx;
					height: 100rpx;
					padding: 50rpx;
				}
			}
		}
	}
</style>